﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using System;

/**
* 获取全国排行，并且检验本地排行
* 
* 1.	设备初始化，将本地排行榜复制到全国榜
* 2.	本地游戏后，检查本地排行榜，如果超过本地排行榜将上传到服务器
* 3.	全国排行榜初始化，设备启动时，逐行检查本地全国排行榜数据，如果本地全国排行榜超过远程则替换本地数据
*/
namespace KFGame
{
    class RankDIO
    {
        public string code;
        public string game;
        public int index;
        public string user;
        public int score;
    }
    public class RankAll : KFTask
    {

        public string server = "http://game.qualityperson.net";

        public string gname = "yysc";

        string url = "/api/index/downloadUserRank";
        string ctag = "downloadUserRank";
        // 全国排行数据文件
        string rank_all_path = Application.streamingAssetsPath + "/rank/rankall.json";
        string rank_path = Application.streamingAssetsPath + "/rank/rank.json";
        // 接收json数据
        public List<RankData> rankAllDatas = new List<RankData>();
        public List<RankData> rankLocalDatas = new List<RankData>();

        int rankIndex = 0;

        void Awake()
        {
            once = true;

        }

        public override void task()
        {

        }

        public void toLoad()
        {
            // 初始化数据
            //initRank();
            // 更新数据
            updateRank();
        }

        public static List<RankData> loadRankAll(string path)
        {

            List<RankData> datas = new List<RankData>();

            if (!File.Exists(path))
            {
                return datas;
            }

            StreamReader reader = new StreamReader(path);
            if (reader == null)
            {
                return datas;
            }

            string RankAllJson = reader.ReadToEnd();
            reader.Close();

            if (RankAllJson.Length <= 0)
            {
                return datas;
            }

            var json = new MiniJSON2.JSON();
            json.serialized = RankAllJson;

            List<RankData> listRank = JsonConvert.DeserializeObject<List<RankData>>(RankAllJson);

            if (listRank == null)
            {
                return datas;
            }

            datas = listRank;

            return datas;

        }
        // 初始化本地全国排行数据
        Boolean initRank()
        {

            rankLocalDatas = loadRankAll(rank_path);
            rankAllDatas = loadRankAll(rank_all_path);
            Array rankall = rankAllDatas.ToArray();

            if (rankLocalDatas != null && rankall.Length <= 0)
            {
                string datasa = JsonConvert.SerializeObject(rankLocalDatas);
                writefiles(rank_all_path, datasa);
                return true;
            }

            return false;
        }

        public static void writefiles(string filePath, string info)
        {
            using (System.IO.FileStream stream = System.IO.File.Open(filePath, System.IO.FileMode.OpenOrCreate))
            {
                byte[] str = System.Text.Encoding.Default.GetBytes(info);
                stream.Write(str, 0, str.Length);
                stream.Flush();
                stream.Close();
            }
        }
        // 更新数据
        void updateRank()
        {
            Debug.Log("update rank");
            // 加载本地全国数据
            rankAllDatas = loadRankAll(rank_all_path);
            int score = 0;
            if (rankAllDatas.Count > rankIndex)
            {
                score = rankAllDatas[rankIndex].count;
            }

            if (rankIndex > 100)
            {
                finish = true;
                return;
            }

            string code = "";
            string user = "";
            string game = gname;
            int index = rankIndex;

            compareRank(code, game, index, user, score);
        }

        void compareRank(string code, string game, int index, string user, int score)
        {
            RankDIO dIO = new RankDIO();
            dIO.code = code;
            dIO.game = game;
            dIO.index = index;
            dIO.user = user;
            dIO.score = score;
            string jsonData = JsonConvert.SerializeObject(dIO);//序列化

            KF.kf.netWorkManager.AsyPost(ctag, server + url, jsonData);

        }

        void Callback(string name, string url, string datas)
        {


            Debug.Log("net call back :" + name + ":" + datas + ": url =" + url);
            var json = new MiniJSON2.JSON();
            json.serialized = datas;

            if (json.ToInt("code") != 1)
                return;

            var data = json.ToJSON("data");
            if (data != null)
            {
                RankData rdata = new RankData();
                rdata.carname = data.ToString("car_code");
                rdata.count = data.ToInt("score");
                rdata.handimg = data.ToString("head");
                rdata.index = rankIndex;
                saveData(rdata);
            }

            rankIndex++;



        }

        void Event(string tag, string url, int id, string message)
        {
            Debug.Log("net call back :" + tag + ":" + id + ": url =" + url);
            if (tag != ctag)
                return;

            if (id == 404)
                return;

            if (id != 200)
                return;


            var json = new MiniJSON2.JSON();
            json.serialized = message;

            if (json.ToInt("code") != 1)
                return;

            var data = json.ToJSON("data");
            if (data != null)
            {
                RankData rdata = new RankData();
                rdata.carname = data.ToString("car_code");
                rdata.count = data.ToInt("score");
                rdata.handimg = data.ToString("head");
                rdata.index = rankIndex;
                saveData(rdata);
            }

            rankIndex++;

        }

        IEnumerator nextrequer()
        {
            yield return new WaitForSeconds(1);
            updateRank();
        }
        void saveData(RankData rdata)
        {
            rankAllDatas = loadRankAll(rank_all_path);
            if (rankAllDatas.Count == rankIndex)
            {
                rankAllDatas.Add(rdata);
            }
            else
            {
                rankAllDatas.Insert(rankIndex, rdata);
            }

            string datasa = JsonConvert.SerializeObject(rankAllDatas);
            writefiles(rank_all_path, datasa);
        }

    }
}